package com.ruoyi.factorydata.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.factorydata.domain.FactoryData;
import com.ruoyi.factorydata.domain.ProductionLineData;
import com.ruoyi.factorydata.domain.StationData;
import com.ruoyi.factorydata.domain.WorkshopData;
import com.ruoyi.factorydata.domain.dto.StationDataDTO;
import com.ruoyi.factorydata.domain.vo.StationDataVo;
import com.ruoyi.factorydata.service.IFactoryDataService;
import com.ruoyi.factorydata.service.IProductionLineDataService;
import com.ruoyi.factorydata.service.IStationDataService;
import com.ruoyi.factorydata.service.IWorkshopDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 工位数据Controller
 * 
 * @author ruoyi
 * @date 2025-06-23
 */
@RestController
@RequestMapping("/stationdata/stationdata")
public class StationDataController extends BaseController
{
    @Autowired
    private IStationDataService stationDataService;

    @Autowired
    private IProductionLineDataService productionLineDataService;

    @Autowired
    private IWorkshopDataService workshopDataService;

    @Autowired
    private IFactoryDataService factoryDataService;

    /**
     * 查询工位数据列表
     */
    @PreAuthorize("@ss.hasPermi('stationdata:stationdata:list')")
    @GetMapping("/list")
    public TableDataInfo list(StationDataDTO stationDataDTO)
    {
        startPage();
        List<StationDataVo> list = stationDataService.selectStationDataList(stationDataDTO);
        TableDataInfo tableDataInfo = new TableDataInfo();
        tableDataInfo.setRows(list);
        tableDataInfo.setTotal(new PageInfo(list).getTotal());
        return tableDataInfo;
    }

    /**
     * 查询工位数据列表
     */
    @PreAuthorize("@ss.hasPermi('stationdata:stationdata:list')")
    @GetMapping("/list/device")
    public TableDataInfo listDevice(StationDataDTO stationDataDTO)
    {
        startPage();
        List<StationDataVo> list = stationDataService.selectStationDataByDeviceList(stationDataDTO);
        TableDataInfo tableDataInfo = new TableDataInfo();
        tableDataInfo.setRows(list);
        tableDataInfo.setTotal(new PageInfo(list).getTotal());
        return tableDataInfo;
    }

    /**
     * 导出工位数据列表
     */
    @PreAuthorize("@ss.hasPermi('stationdata:stationdata:export')")
    @Log(title = "工位数据", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, StationDataDTO stationDataDTO)
    {
        List<StationDataVo> list = stationDataService.selectStationDataList(stationDataDTO);
        ExcelUtil<StationDataVo> util = new ExcelUtil<StationDataVo>(StationDataVo.class);
        util.exportExcel(response, list, "工位数据数据");
    }

    /**
     * 获取工位数据详细信息
     */
    @PreAuthorize("@ss.hasPermi('stationdata:stationdata:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        StationData stationData = stationDataService.selectStationDataById(id);
        ProductionLineData productionLineData = productionLineDataService.selectProductionLineDataById(stationData.getProductionLineId());
        WorkshopData workshopData = workshopDataService.selectWorkshopDataById(productionLineData.getWorkshopId());
        FactoryData factoryData = factoryDataService.selectFactoryDataById(workshopData.getFactoryId());
        return AjaxResult.success(StationDataVo.builder()
                .id(stationData.getId())
                .name(stationData.getName())
                .stationCode(stationData.getStationCode())
                .productionLineId(productionLineData.getId())
                .productionLineName(productionLineData.getName())
                .workshopId(workshopData.getId())
                .workshopName(workshopData.getName())
                .factoryId(factoryData.getId())
                .factoryName(factoryData.getFactoryName())
                .remarks(stationData.getRemarks())
                .delFlag(stationData.getDelFlag())
                .version(stationData.getVersion())
                .createBy(stationData.getCreateBy())
                .createTime(stationData.getCreateTime())
                .updateTime(stationData.getUpdateTime())
                .build()
        );
    }

    @GetMapping("/selectStationByKeyword")
    public AjaxResult selectStationByKeyword(@RequestParam(required = false) String keyword,
                                                    @RequestParam(required = false) Long productionLineId) {
        startPage();
        List<StationData> list = stationDataService.list(new QueryWrapper<StationData>().lambda()
                .eq(productionLineId != null, StationData::getProductionLineId, productionLineId)
                .like(keyword != null && !keyword.isBlank(), StationData::getName, keyword));
        return AjaxResult.success(list);
    }
    /**
     * 新增工位数据
     */
    @PreAuthorize("@ss.hasPermi('stationdata:stationdata:add')")
    @Log(title = "工位数据", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody StationData stationData)
    {
       boolean exists = stationDataService.lambdaQuery()
            .eq(StationData::getStationCode, stationData.getStationCode()).count() > 0;
       if (exists){
           return AjaxResult.warn("工位编码已存在");
       }
       stationData.setCreateBy(getUserId().toString());
       return toAjax(stationDataService.insertStationData(stationData));
    }

    /**
     * 修改工位数据
     */
    @PreAuthorize("@ss.hasPermi('stationdata:stationdata:edit')")
    @Log(title = "工位数据", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody StationData stationData)
    {
        List<Long> ids = stationDataService.lambdaQuery()
                .eq(StationData::getStationCode, stationData.getStationCode())
                .select(StationData::getId).list().stream()
                .map(StationData::getId)
                .collect(Collectors.toList());
        boolean exists = !ids.isEmpty() && !ids.contains(stationData.getId());
        if (exists){
            return AjaxResult.warn("工位编码已存在");
        }
        return toAjax(stationDataService.updateStationData(stationData));
    }

    /**
     * 删除工位数据
     */
    @PreAuthorize("@ss.hasPermi('stationdata:stationdata:remove')")
    @Log(title = "工位数据", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(stationDataService.deleteStationDataByIds(ids));
    }
}
